package com.bsh.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bsh.mybatis.model.Module;
import com.bsh.service.ModuleService;

/**
 * @author gsh
 * @since 0.0.1
 * 
 */
@Controller
public class AuthController {
	private static Logger log = LoggerFactory.getLogger(IndexController.class);
	@Autowired
	HttpServletRequest request;
    @Autowired
    HttpServletResponse response;
    @Autowired
    HttpSession session;    
    @Autowired
    ModuleService module;
    	
	/**
	 * 用户登录 ajax
	 */
	@RequestMapping(value = "/ajaxLogin",method=RequestMethod.POST)
	@ResponseBody
	public String ajaxLogin(@RequestParam(value="name") String loginName,@RequestParam(value="psw") String password) {
		boolean logined = false;
		try {
			Subject currentUser = SecurityUtils.getSubject();
			if (currentUser.isAuthenticated()) {
				currentUser.logout();
			}
			UsernamePasswordToken token = new UsernamePasswordToken(loginName, password);
			token.setRememberMe(false);
			currentUser.login(token);
		} catch (Exception ex) {

		}

		logined = SecurityUtils.getSubject().isAuthenticated();
		String msg = "";
		if (logined) {
		   msg="登录成功！";	
		}
		return msg;
	}
    
	 /**
     * 用户登录
     */
    @RequestMapping(value = "/login")
    public ModelAndView login(){
    	ModelAndView mv = new ModelAndView("forward:/login.jsp");
    	return mv;
    }
	
    /**
     * 用户登录
     */
    @RequestMapping(value = "/login/chk",method=RequestMethod.POST)
    public ModelAndView loginView(@RequestParam(value="name") String loginName,
    		@RequestParam(value="psw") String password,
    		@RequestParam(value="imgcode") String imgcode,
    		@RequestParam(value="rem") String isRemember) {    	
    	ModelAndView mv = new ModelAndView("forward:/login.jsp"); 
    	mv.addObject("name",loginName);
    	
        if (StringUtils.isEmpty(loginName)||StringUtils.isEmpty(password)) {
            mv.addObject("msg","请输入用户名和密码！");
            return mv;
        }
        if (StringUtils.isEmpty(imgcode)) {
            mv.addObject("msg","请输入验证码！");
            return mv;
        }
        String serverCheckcode = (String) request.getSession().getAttribute("checkcode");
        if (!imgcode.toUpperCase().equals(serverCheckcode)) {
            mv.addObject("msg","验证码错误！");
            return mv;
        }
    	
    	boolean logined = false;
        try {
            Subject currentUser = SecurityUtils.getSubject();
            if (currentUser.isAuthenticated()) {
                currentUser.logout();
            }
            UsernamePasswordToken token = new UsernamePasswordToken(loginName.trim(), password.trim());
            token.setRememberMe((","+isRemember+",").contains(",1,"));
            currentUser.login(token);
        } catch(AuthenticationException authex){
        	if("USER_NOT_EXISTS".equals(authex.getMessage())){
                mv.addObject("msg","用户不存在！");
                return mv;
        	}else if("USER_DISABLED".equals(authex.getMessage())){
                mv.addObject("msg","用户已禁用！");
                return mv;
        	}
        }catch (Exception ex) {        	       
        	log.info(ex.getMessage());
        }

        logined = SecurityUtils.getSubject().isAuthenticated();
        if (logined) {
        	List<Module> listMod = module.getAllModule();
        	session.setAttribute("module_list",listMod);
        	      	
            mv = new ModelAndView("redirect:/main");
            mv.addObject("msg","登录成功！");
            return mv;
        }
        
        mv.addObject("msg","用户名或密码错误！");
        return mv;
    }

    /**
     * 退出
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout2")
    public ModelAndView logout(HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.logout();
        }
        request.getSession().invalidate(); 
        return new ModelAndView("redirect:/login");
    }
}
